//
//  BmdtViewController.m
//  shanghaiyangpu4
//
//  Created by FrankChen on 13-3-16.
//  Copyright (c) 2013年 FrankChen. All rights reserved.
//

#import "BmdtViewController.h"
#import "YpywCellView.h"

#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define IOS_VERSION_7_OR_ABOVE (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)? (YES):(NO))

#import "KKWebServiceManager.h"

@interface BmdtViewController ()

@end

@implementation BmdtViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    // test data
    //[(UILabel *)[self.view.superview viewWithTag:49]setText:@"杨浦新闻"];

    
    if (iPhone5) {
        diff=88;
    }else{
        diff=0;
    }
    if (IOS_VERSION_7_OR_ABOVE) {
        diff=diff+20;
    }
    _loadMoreCount = 1;
    _dataSource = [[NSMutableArray alloc] initWithCapacity:4];
    _linkSource= [[NSMutableArray alloc] initWithCapacity:4];
    _net=[[xwzx alloc]init];
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 10.0, 0);
    
    // set header
    [self createHeaderView];
    
    // the footer should be set after the data of tableView has been loaded, the frame of footer is according to the contentSize of tableView
    // here, actually begin too load your data, eg: from the netserver
    
    [self showRefreshHeader:YES];
    [NSThread detachNewThreadSelector:@selector(testFinishedLoadData) toTarget:self withObject:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark overide UITableViewDataSource methods


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //    return _dataSource?1:0;
    return self.arr_infoItem.count ? 1 : 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    return _dataSource?_dataSource.count:0;
    return self.arr_infoItem.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    YpywCellView *cell1=[[[YpywCellView alloc]initWithFrame:CGRectMake(15, 0, 290, 40)]autorelease];
    
    UITableViewCell *cell =[[[UITableViewCell alloc]init]autorelease];
    cell= [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
        [cell.contentView addSubview:cell1];
    }
    
//	// Configure the cell.
//    if (_dataSource && indexPath.row < _dataSource.count) {
//        NSString *content=[_dataSource objectAtIndex:indexPath.row];
//        NSRange range=[content rangeOfString:@" 2"];
//        cell1.time= [content substringFromIndex:(range.location+1)];
//        cell1.title= [content substringToIndex:(range.location)];
//        [cell1 inputData];
//    }
    
    KKInfoItem *infoItem = [self.arr_infoItem objectAtIndex: indexPath.row];
    cell1.time = infoItem.kk_InfoDate;
    cell1.title = infoItem.kk_title;
    [cell1 inputData];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50.0;
}
//click tableview cell event
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
    
    HUD.delegate = self;
    HUD.labelText = @"Loading";
    
    row=indexPath.row;
    
    [HUD showWhileExecuting:@selector(doIt) onTarget:self withObject:Nil animated:true];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //[HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:Nil animated:true];
//    [self performSelectorOnMainThread:@selector(myProgressTask) withObject:nil waitUntilDone:NO];
    
    [self kk_didSelectedItemWithIndexPath: indexPath];
    
}

-(void)doIt{
    sleep(1);
}

- (void)myProgressTask {
    // This just increases the progress indicator in a loop
    [self addLabel:row];
}

-(void) addLabel:(int)tableRow{
   
    NSString *infoId= [_linkSource objectAtIndex:tableRow];
    NSString *content=[[[NSString alloc]init]autorelease];
    [_net getData:infoId];
    content=_net.content;
    
        NSString *title=[[[NSString alloc]init]autorelease];
        title=[_dataSource objectAtIndex:tableRow];
        
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
        view.backgroundColor=[UIColor clearColor];
        UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 117+diff/1.7, 320, 300+diff/1.7)];
        UIColor *color=[UIColor whiteColor];
        scrollView.backgroundColor=color;
        
        UIFont *font=[UIFont fontWithName:@"FZHTJW--GB1-0" size:16.0f];
        CGSize size=CGSizeMake(300, 500000);
        
        UILabel *lbl_title=[[UILabel alloc] initWithFrame:CGRectZero];
        [lbl_title setNumberOfLines:0];
        
        NSDictionary * tdic=[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
        title=[title stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
        CGSize lblsize1;
        if (IOS_VERSION_7_OR_ABOVE) {
            lblsize1=[title boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:Nil].size;
            
        }
        else{
            lblsize1=[title sizeWithFont:font constrainedToSize:size];
        }

        lbl_title.frame=CGRectMake(10, 0, 300, lblsize1.height);
        lbl_title.backgroundColor=[UIColor colorWithRed:0.937 green:0.918 blue:0.906 alpha:1];
        lbl_title.textColor=[UIColor darkGrayColor];
        lbl_title.font=font;
        lbl_title.textAlignment=NSTextAlignmentCenter;
        lbl_title.text=title;
        
        CGSize lblsize;
        if (IOS_VERSION_7_OR_ABOVE) {
            lblsize=[content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:Nil].size;
            
        }
        else{
            lblsize=[content sizeWithFont:font constrainedToSize:size];
        }
        
        UILabel *lbl_content=[[UILabel alloc] initWithFrame:CGRectMake(15, lblsize1.height+10, 300, lblsize.height+20)];
        [lbl_content setNumberOfLines:0];
        //lbl_content.frame=CGRectMake(0, 15, lblsize.width, lblsize.height+30);
        lbl_content.backgroundColor=[UIColor colorWithRed:0.937 green:0.918 blue:0.906 alpha:1];
        lbl_content.textColor=[UIColor darkGrayColor];
        lbl_content.font=font;
        
        
        lbl_content.text=content;
        
        [scrollView addSubview:lbl_content];
        [scrollView addSubview:lbl_title];
        
        [scrollView setContentSize:CGSizeMake(320, lblsize.height+lblsize1.height+100)];
        
        [scrollView setBackgroundColor:[UIColor colorWithRed:0.937 green:0.918 blue:0.906 alpha:1]];
        
        [self AddBtn_back];
        [view addSubview:scrollView];
        [view addSubview:btn_Back];
        _view1=view;
        
        [HUD removeFromSuperview];
        [HUD release];
        //[self.view.viewForBaselineLayout setHidden:true];
        [self.view.superview addSubview:view];
    
}

-(void)AddBtn_back{
    CGRect frame=CGRectMake(21, 87+diff/1.7, 72, 29);
    UIButton *btn_back=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn_back setTag:51];
    [btn_back setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
    btn_back.frame=frame;
    [btn_back addTarget:self action:@selector(Btn_back_Clicked) forControlEvents:UIControlEventTouchUpInside];
    //[[self view]addSubview:btn_back];
    btn_Back=btn_back;
}

-(void)Btn_back_Clicked{
    //UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"show" message:@"1" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    //[alert show];
    
    [_view1 removeFromSuperview];
    //[_view.viewForBaselineLayout setHidden:true];
    [btn_Back removeFromSuperview];
    
}


#pragma mark-
#pragma mark overide methods
-(void)beginToReloadData:(EGORefreshPos)aRefreshPos{
	[super beginToReloadData:aRefreshPos];
    
    if (aRefreshPos == EGORefreshHeader) {
        // pull down to refresh data
        [self performSelector:@selector(testRealRefreshDataSource) withObject:nil afterDelay:0.0];
    }else if(aRefreshPos == EGORefreshFooter){
        // pull up to load more data
        [self performSelector:@selector(testRealLoadMoreData) withObject:nil afterDelay:0.0];
    }
}
//下拉刷新
-(void)testRealRefreshDataSource{
    //NSInteger count = _dataSource?_dataSource.count:0;
    
    //[_dataSource removeAllObjects];
    _dataSource=nil;
    _dataSource = [[NSMutableArray alloc] initWithCapacity:4];
    _linkSource=nil;
    _linkSource = [[NSMutableArray alloc] initWithCapacity:4];
    
    [self testFinishedLoadData];
    
    // after refreshing data, call finishReloadingData to reset the header/footer view
    [_tableView reloadData];
    [self finishReloadingData];
}

//上拉加载
-(void)testRealLoadMoreData{
    @try {
        if(_loadMoreCount<20){
            
            [KKWebServiceManager kk_getModuleId: KK_BMDT pageIndex: _loadMoreCount success:^(id response) {
                
                if ([response isKindOfClass: [NSArray class]]) {
                    [self.arr_infoItem addObjectsFromArray: response];
                }
                
                // after loading data, should reloadData and set the footer to the proper position
                [self.tableView reloadData];
                [self finishReloadingData];
                [self setFooterView];
                _loadMoreCount++;
                
            } faile:^{
                
            }];
            return;
            
            [_net getTile:@"yangpuyaowen" :_loadMoreCount];
            
            for(int i=0;i<20;i++){
                if (_dataSource == nil) {
                    _dataSource = [[NSMutableArray alloc] initWithCapacity:4];
                    _linkSource = [[NSMutableArray alloc] initWithCapacity:4];
                }
                [_dataSource addObject:[[_net titleArray] objectAtIndex:i]];
                [_linkSource addObject:[[_net linkArray] objectAtIndex:i]];
            }
            _loadMoreCount++;
        }
        else{
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"加载已至上限，无法加载更多" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }
        // after refreshing data, call finishReloadingData to reset the header/footer view
        [_tableView reloadData];
    }
    @catch (NSException *exception) {
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"部门动态已显示全部" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];
    }
    @finally {
        [self finishReloadingData];
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [self setFooterView];
    }


    
}

-(void)testFinishedLoadData{//绑定初始数据
    
    self.arr_infoItem = [NSMutableArray array];
    
    [KKWebServiceManager kk_getModuleId: KK_BMDT pageIndex: 1 success:^(id response) {
        
        if ([response isKindOfClass: [NSArray class]]) {
            [self.arr_infoItem addObjectsFromArray: response];
        }
        
        // after loading data, should reloadData and set the footer to the proper position
        [self.tableView reloadData];
        [self finishReloadingData];
        [self setFooterView];
        _loadMoreCount=2;
        
    } faile:^{
        
    }];
    return;
    
[_net getTile:@"bumendongtai" :1];

    
        //_dataSource=[NSMutableArray arrayWithArray:_net.titleArray];
        for(int i=0;i<[_net titleArray].count;i++){
            [_dataSource addObject:[[_net titleArray] objectAtIndex:i]];
            [_linkSource addObject:[[_net linkArray] objectAtIndex:i]];
        }
        // after loading data, should reloadData and set the footer to the proper position
        [self.tableView reloadData];
        
    
    [self finishReloadingData];
    [self setFooterView];
    _loadMoreCount=2;
}


@end
